var cartDomain = ehaier.domainUrl.cartDomain;
var itemDomain = ehaier.domainUrl.itemDomain;
var memberDomain = ehaier.domainUrl.memberDomain;
var phpDomain = ehaier.domainUrl.phpDomain;
var basePrice;

var pdetailMinCart = {};
pdetailMinCart = new MMJS.Cart();
pdetailMinCart.bind('.js_cart');
var firstEnterPage = 1;
var ladderPrices = [];

var buyBtnHtml = '<a class="a-to-cart btnSendCar js_add_to_cart" href="javascript:void();" id="buynow" style="background-position: 18px 0px;"></a><a class="a-to-cart btnSendCar js_add_to_cart" href="javascript:void(0);" id="buyIt"></a>';
var invoiceInfoHtml = '<p id="jsInvoiceInfoHtml" style="margin-left:50px;margin-top:34px;">日日顺商城作为全国首批电子发票试点网上商城，于2014年3月31日起全面推行<a class="txt_red"' + 
    'href="' + phpDomain + '/helpcenter.php?id=77&amp;ebi=ref-ix-ft-1-a-2-5">电子发票</a>' +
    '</p>';
//var noStockHtml = '<span class="s-store s-store-lack" id="nostock" title="暂时无货">暂时无货</span>';
var noStockHtml = '<a href="javascript:showArrival();"><span class="s-store s-store-arrival" id="nostock" title="该商品到货后，我们将发短信通知您">到货通知</span></a>';

var predetermineHtml = '<a class="a-store a-predetermine" id="predetermine" href="javascript:doPredetermine();" title="我要预订"></a>';

// 全额预售 20160318 begin
var presaleNoStartHtml = '<span class="s-store a-presalehide" id="presalehide" title="未开始"></span><span style="line-height: 44px;" id="times">活动还未开始，请稍后再来</span>';//预售未开始
var presaleHtml = '<a class="a-store a-presale" id="presale" href="javascript:doPresale();"></a><span style="line-height: 44px;" id="times"></span>';//预售抢购
var presaleStopHtml = '<span class="s-store a-presalehide" id="presalehide" title="未开始"></span><span style="line-height: 44px;" id="times">活动已结束</span>';//预售结束
// 全额预售 20160318 end

//限时抢购/秒杀 20160520 begin
var flashSaleHtml = '<a class="a-to-cart btnSendCar js_add_to_cart" id="flashSale" href="javascript:doFlashSale();" style="background-position: -189px -398px;"></a>';
var flashSaleButten = 0;
//限时抢购/秒杀 20160520 end

//默认最小购买数量为1
var minBuyNum = 1;
//立即购买按钮
var buyAddOrderBtnHtml = '<a class="a-to-cart btnSendCar js_add_to_cart" href="javascript:void(0);" style="background-position: 18px 0px;" id="custmizebuyIt"></a>';
var isMainProStock = true;//主商品是否有货

(function ($) {
	
    $.fn.get_fe_data = function () {//序列号获取表单数据

        var $named_fe = $(this).find('input,textarea,select').filter("[name!='']");

        var post_data = {};

        $named_fe.each(function () {

            var $fe = $(this);

            var tag_name = $fe.get(0).tagName.toLowerCase();

            var type = ( $fe.attr('type') || '' ).toLowerCase();

            var name = $fe.attr('name');


            switch (tag_name) {

                case 'input':

                    switch (type) {

                        case 'checkbox':

                            if ($fe.is(':checked')) {

                                if (typeof post_data[name] == 'undefined') {

                                    post_data[name] = [];

                                }

                                post_data[name].push($fe.val());

                            }

                            break;

                        case 'radio':

                            if ($fe.is(':checked')) {

                                post_data[name] = $fe.val();

                            }

                            break;

                        default:

                            post_data[name] = $fe.val();

                            break;

                    }

                    post_data[name] = $fe.val();

                    break;

                case 'textarea':

                case 'select':

                    post_data[name] = $fe.val();

                    break;

            }

        });

        return post_data;

    }


})(jQuery);


function loadComment(itemId) {

    var timestamp = Date.parse(new Date());

    var pi = $('#main-comments-list>div').size() + 1;

    var commentType = $("#comment-type").val();

    var ps = $("#ps").val();

    var pc = getPageCount(commentType);

    var url = itemDomain + "/product/loadComment?itemId=" + itemId + "&pageId=" + pi + "&pageSize=" + ps + "&type=" + commentType + "&t=" + timestamp;

    $.get(url,

        function (result) {

            if (result.indexOf("<!--OK-->") != -1) $("#main-comments-list").append(result);

        });

    if (pi >= parseInt(pc)) {

        // 最后一页了.

        $("#more-comment").hide();

    }

}

function changeCommentDetail(obj, itemId, commentType) {
    $("ul[class='tab'] li").each(function (i) {

        $(this).removeClass('curr');

    });

    $(obj).parent().addClass("curr");

    var oldType = $("#comment-type").val();

    var pi = 1;

    $("#more-comment").show("");

    var ps = $("#ps").val();

    var pc = getPageCount(commentType);

    if (pc == 0) {

        $("#main-comments-list").html("暂无评价");

    }

    var url = itemDomain + "/product/comment/" + itemId + ".html?pageId=" + pi + "&pageSize=" + ps + "&type=" + commentType;

    window.location.href = url;
    $("#comment-type").val(commentType);

}


function changeComment(obj, itemId, commentType) {

    $("ul[class='tab'] li").each(function (i) {

        $(this).removeClass('curr');

    });

    $(obj).parent().addClass("curr");

    var oldType = $("#comment-type").val();

    var pi = 1;

    $("#more-comment").show("");

    var ps = $("#ps").val();

    var pc = getPageCount(commentType);

    if (pc == 0) {

        $("#main-comments-list").html("暂无评价");

    }


    var timestamp = Date.parse(new Date());

    var url = itemDomain + "/product/comment/" + itemId + "_byajax.html?pageId=" + pi + "&pageSize=" + ps + "&type=" + commentType;

    $('#commentWrapper').load(url);
//    $.get(url,
//
//    function(result) {
//
//        if (result.indexOf("<!--OK-->") != -1) $("#main-comments-list").html(result);
//
//    });

    if (pi >= parseInt(pc)) {

        // 最后一页了.

        $("#more-comment").hide();

    }

    $("#comment-type").val(commentType);

}

function getPageCount(commentType) {

    var pc = 1;

    var domId = commentType + "-count";

    var rc = $("#" + domId).val();

    var ps = $("#ps").val();

    pc = parseInt(rc / ps);

    if (rc % ps != 0) {

        pc++;

    }

    return pc;

}

function showReply(id) {

    var dom = "comment_reply_" + id;

    $("#" + dom).show();

    $("#" + dom).find('#txtrea_comment_' + id).val('');

    $("#" + dom).find('#txtrea_comment_' + id).focus();

    $("#comment_btn_" + id).hide();

    return false;

}

function addReply(id) {

    try {
        var mid = parent.document.getElementById('commentUserId').value;

        var mname = parent.document.getElementById('commentUserName').value;

        var memberId = $('#comment_reply_memberId_' + id).val();

        if (memberId == undefined) {
            memberId = -1;
        }

        var commentId = $('#comment_reply_commentId_' + id).val();

        var content = $('#txtrea_comment_' + id).val();


    } catch (e) {

        $('#comment_reply_msg_' + id).html("请先登陆");

        ajaxLogin();

        return;

    }

    if (mid == '' || mname == '') {

        ajaxLogin();

        return;

    }

    var content = $('#txtrea_comment_' + id).val();

    // if (content == '') {


    if ($.trim(content).length <= 0 || $.trim(content).length > 100) {

        $('#comment_reply_msg_' + id).html("回复内容长度在1-100个字之间");

        return;

    }
    //content = content.replace('#','%23');
    $.ajax({
        type: "post",
        url: itemDomain + "/product/comment/addCommentReply.html",
        data: "content=" + content + "&comment_id=" + commentId + "&member_id=" + memberId + '&' + getCSRFTokenParam(),
        async: false,
        success: function (data) {
            $("#comment_reply_msg_" + id).fadeIn().html(data.data.message);
            //$("#comment_reply_msg_" + id).;
            $("#comment_reply_" + id).hide();
            refrushCSRFToken(data.csrfToken);
        }
    });
    setTimeout(function () {
        $("#comment_reply_msg_" + id).fadeOut()
    }, 5000);
}

function showAddQuestion(){
    try {
        var mid = ehaier.domainUrl.uid;
    } catch (e) {
        ajaxLogin();
        return;
    }

    if (mid == '' || mid == 0) {
        ajaxLogin();
        return;
    }

    $('.so-popbox-mask').show();
	$('.ajax-popInfoBox').show();
}

function getByteLen(val) {
	var len = 0;
	for (var i = 0; i < val.length; i++) {
		if (val[i].match(/[^\x00-\xff]/ig) != null) // 全角
			len += 2;
		else
			len += 1;
	}
	return len;
} 



function addQuestion(){
    var productId = $("#currentProductIdHidden").val();
    $("#productQuestions").text($("#productQuestions").val());
    var question = $("#productQuestions").text();
    var cateType= $("#currentQuestionTypeId").val();
    if (getByteLen(question) <= 0){
    	 $("#productQuestions").attr("placeholder","咨询内容不能为空");
    	 $("#productQuestions").focus();
    	 return;
    }
    if (getByteLen(question) > 512){
    	$('.so-popbox-mask').hide();
    	$('.ajax-popInfoBox').hide();
    	$.sobox.alert('提示', '咨询内容请不要超过255个字，请再次点"我要咨询"减少内容后提交！');
    	return;
    }
    $.ajax({
        type : "post",
        url : itemDomain + "/product/question/addQuestion.html",
        data: "productId=" + productId + "&question=" + encodeURIComponent(question) + "&questionType=" + cateType +  "&" +getCSRFTokenParam(),
        contentType: "application/x-www-form-urlencoded; charset=utf-8", 
        success : function(data){
        	 $('.so-popbox-mask').hide();
			 $('.ajax-popInfoBox').hide();
            if (data.data.code==0){
            	 $.sobox.alert('提示', '您的咨询已提交成功！我们将尽快回复您！');
            	 $("#productQuestions").val('');
                 refrushCSRFToken(data.csrfToken);
            }else{
            	$.sobox.alert('提示', data.data.message);
                refrushCSRFToken(data.csrfToken);
            }
        },
        error:function(){
        	$('.so-popbox-mask').hide();
			 $('.ajax-popInfoBox').hide();
        	$.sobox.alert('提示', '抱歉，您的咨询未能提交成功，请稍后再试！');
            refrushCSRFToken(data.csrfToken);
        }
    });
}

function addCollect(productId){
	try {
        var mid = ehaier.domainUrl.uid;
    } catch (e) {
        ajaxLogin();
        return false;
    }

    if (mid == '' || mid == 0) {
        ajaxLogin();
        return false;
    }
	
    $.ajax({
        type : "post",
        url : itemDomain + "/product/collect/addCollect.html",
        data: "productId=" + productId + "&" +getCSRFTokenParam(),

        success : function(data){
            if (data.data.code == 0){
                $.sobox.alert('提示','收藏成功');
                refrushCSRFToken(data.csrfToken);
            }else if (data.data.code == 1){
                ajaxLogin();
                refrushCSRFToken(data.csrfToken);
            }else if (data.data.code == -1){
                $.sobox.alert('提示','您已收藏过该商品！');
                refrushCSRFToken(data.csrfToken);
            }
        },
        error:function(){
            alert("处理失败，请稍后再试！")
            refrushCSRFToken(data.csrfToken);
        }
    });
}

function ajaxLogin() {
    var ajaxUrl = memberDomain + "/ajaxLogin?callback=?";
    $.getJSON(ajaxUrl, function (data) {
        var ajaxPop = $.sobox.pop({
            cls: 'ajax-popInfoBox',
            title: '用户登录',
            defaultShow: true,
            visibility: true,
            onlyOne: true,
            width:340,
            content: data.data,
            callback: function () {
                $('.ajax-popInfoBox .h2-sopop .s-title').text('用户登录');
                $('.ajax-popInfoBox').css('visibility', 'visible').hide().fadeIn('fast');
            }
        });
        
        //ajaxPop.showPop();
        //$('body').data('ajaxPop', ajaxPop);
    });


}


var ehaier = ehaier || {};

ehaier.product = {

    init: function () {

        var that = this;

        that.base();//基础及零碎

        that.galleryPreview();//相册滚动及放大镜


        //that._popShowGallery();//弹出窗显示相册

        that._stockMessage();//到货通知

        that._scrollTabtitle();//滚动内容tab标题

        that._scrollLoadCont();//滚动加载内容

        that._groupProScrollEvent();//套装滚动事件

        that._popGallery();

        that._sharePro();//share

    },

    base: function () {

        var that = this;

        //收藏商品

        /*        $(document).on('click', '.a-fav-product', function () {


         that.js_tz_sc_toCart({obj: this, popTitle: '.h2-popTip', css: {'width': '320px', 'marginLeft': '-160px'}});

         return false;

         });*/


        //咨询

        /*$('.a-link-consult').click(function () {

            that.js_tz_sc_toCart({obj: this, popTitle: '.h2-popComment', css: {'width': '610px', 'marginLeft': '-305px'}});

            return false;

        });*/


        //details-cont

        if ($('.details-cont').length) {

            $('.details-cont').soChange({

                thumbObj: '.ul-details-tab .li-tab',

                thumbNowClass: 'li-now',

                slideTime: 0,

                autoChange: false,

                thumbOverEvent: false

            });

        }


        if ($('.ul-rank-cont').length) {

            $('.ul-rank-cont').soChange({

                thumbObj: '.h2-rank-tab',

                thumbNowClass: 'h2-rank-tab-now',

                autoChange: false,

                slideTime: 0

            });

        }


    },

    _sharePro: function () {

        var proTitle = $('.product-title .s-title').text();

        var proAbs = $('.product-abs').text();

        $('.s-share').soShare({

            pic: $('.img-bigshow').attr('src'),

            content: encodeURIComponent(proTitle + ' ' + proAbs)

        });

    },

    _scrollLoadCont: function () {

        var that = this;

        if ($('.packageGroups').length) {

            var lazyCont = {one: false, two: false};

            var $tttop = parseInt($('.packageGroups').position().top);

            var ts = $(window).height() + $(window).scrollTop();
            if (ts > $tttop) {//判断采用哪种方式缓加载


                window.onload = function () {

                    if (lazyCont.one === false) {
                        loadProInfo();
                    }
                };

            }


            $(window).bind('scroll', scrollE);


            $('.li-tab-services').click(function () {

                if (lazyCont.two === false) {

                    var servicesHtml = $('#txta-services').val();

                    $('.details-services').html(servicesHtml);

                    lazyCont.two = true;

                }

            });

        }

        function scrollE() {

            var scrollT = parseInt($(window).scrollTop()) + $(window).height();

            if ((lazyCont.one === false) && (scrollT > $tttop)) {

                loadProInfo();

                $(window).unbind('scroll', scrollE);//解绑window scroll load事件

            }

        }


        function loadProInfo() {//执行load事件

            $('.details-proinfo').html($('#txta-proinfo').val());

            lazyCont.one = true;//不再执行标识

            loadBfdCol();//百分点推荐栏lazy处理


            //that._scrollTabtitle();//标题切换随屏滚动

        }


        //var loadn = 1;

        function loadBfdCol() {

            //console.log(loadn);

            if ($('.bfd_show_list').length) {

                $('.bfd_show_list').soLazy();
            } else {

                setTimeout(function () {

                    loadBfdCol();

                    //loadn++;

                }, 2000);

            }

        }


    },


    /*    _scrollTabtitle : function () {//滚动内容tab标题

     if ($('.details-tab-title').length) {

     function getInfo(o) {

     return {left : o.offset().left,posLeft : o.position().left,cssPos : o.css('position'),cssTop : o.css('top'),cssLeft : o.css('left')}

     }

     var $aO = $('.details-tab-title'),$bO = $('.consult-tab-title'),$cO = $('.p-consult-link'),atop,btop,ctop;

     var $aInfo = getInfo($aO), $bInfo = getInfo($bO);

     var $aClone =$aO.clone(), $bClone = $aO.clone();





     function getAbcTop() {

     setTimeout(function () {

     atop = parseInt($('.details-cont-main').offset().top);

     btop = parseInt($bO.offset().top);

     ctop = parseInt($cO.offset().top);

     //console.log(atop+','+btop+','+ctop);

     },600);

     }



     function scrollBegin(o,oClone,oInfo,nt,aClass) {

     o.addClass(aClass).after(oClone);

     o.css({

     position:'fixed',

     top:'1px',

     left:oInfo.left,

     zIndex:'105'

     });

     var ie6 = (typeof document.body.style.maxHeight == "undefined");

     if (ie6) {//ie6事件

     o.css({position:'absolute',

     top:nt+1,

     left:oInfo.posLeft

     });

     }

     }

     function scrollEnd(o,oClone,oInfo,rClass) {

     if (oClone) {oClone.remove();}

     o.removeClass(rClass).css({

     position:oInfo.cssPos,

     left:oInfo.cssLeft,

     top:oInfo.cssTop,

     zIndex:'0'

     });

     }



     getAbcTop();



     $('.strong-comm-count').click(function () {
     $('.ul-details-tab .li-tab').eq(3).trigger('click');

     window.scrollTo(0,atop);

     });



     $aO.find('.li-tab').click(function () {

     if (parseInt($(window).scrollTop())>atop) {window.scrollTo(0,atop);}

     getAbcTop();

     });

     $bO.find('.li-tab').click(function () {

     // if (parseInt($(window).scrollTop())>btop) {window.scrollTo(0,btop);}

     $(this).siblings().removeClass('li-now').end().addClass('li-now');

     $('.details-consult').load(($(this).attr('ajaxurl')),function () {

     getAbcTop();

     });

     return false;

     });

     $(window).scroll(function () {

     var nt = parseInt($(window).scrollTop());

     if (nt>atop&&nt<btop-42) {

     scrollBegin($aO,$aClone,$aInfo,nt,'details-tab-title-scroll');

     }else {

     scrollEnd($aO,$aClone,$aInfo,'details-tab-title-scroll');

     }

     if (nt>btop&&nt<ctop-42) {

     scrollBegin($bO,$bClone,$bInfo,nt,'consult-tab-title-scroll');

     }else {

     scrollEnd($bO,$bClone,$bInfo,'consult-tab-title-scroll');

     }

     });



     // scroll tabtitle end

     $('.details-consult .p_page a').live('click',function () {

     $('.details-consult').load(this.href);

     window.scrollTo(0,btop);

     return false;

     });



     }

     },*/
    _scrollTabtitle: function () { //滚动内容tab标题
    	
    	if (!$('.details-tab-title').length) {
    		return false;
    	}
    	
        var
            mainTabTitle = $('.details-tab-title'),
            subTabTitle = $('.consult-tab-title'),
            consult = $('.details-consult'),
            mainTabTitleClone = mainTabTitle.clone().hide().insertAfter(mainTabTitle),
            subTabTitleClone = subTabTitle.clone().hide().insertAfter(subTabTitle),
            mainTabTitleInitVal = mainTabTitle.offset().top;

        // fixed定位hack

        var fix = (function () {

//            if ( $.browser.mise && $.browser.version == '6.0' ) {
//                return function(element, position) {
//
//                    var
//                        docWidth    = $(document).width(),
//                        docHeight   = $(document).height(),
//                        scrollTop   = $(window).scrollTop(),
//                        innerHeight = $(window).height();
//
//                    $(element).css({
//                        position: 'absolute',
//                        left   : typeof parseInt( position.left )   === 'number' ? position.left  : 'auto',
//                        top    : typeof parseInt( position.top  )   === 'number' ?  parseInt( position.top ) + scrollTop : 'auto' ,
//                        right  : typeof parseInt( position.right)   === 'number' ? position.right  : 'auto',
//                        bottom : typeof parseInt( position.bottom ) === 'number' ? ( docHeight - innerHeight - scrollTop + parseInt(position.bottom)) :'auto'
//                    });
//
//                };
//            }

            return function (element, position) {
                $(element).css({
                    position: 'fixed',
                    left: position.left,
                    top: position.top,
                    right: position.right,
                    bottom: position.bottom

                });
            }

        }());

        // TabTitle滚动跟随效果
        /*
        $(window).on('scroll', function (event) {

            var
                scrollTop = $(this).scrollTop(),
                mainTabTitleOffset = mainTabTitle.css('position') == 'fixed' ?
                    mainTabTitleClone.offset() :
                    mainTabTitle.offset(),
                subTabTitleOffset = subTabTitle.css('position') == 'fixed' ?
                    subTabTitleClone.offset() :
                    subTabTitle.offset();

            if (scrollTop >= mainTabTitleOffset.top &&
                scrollTop <= subTabTitleOffset.top - mainTabTitle.height()) {
                mainTabTitleClone.show();
                mainTabTitle.css('z-index', 110);
                fix(mainTabTitle, {top: 0});

            } else {
                mainTabTitleClone.hide();
                mainTabTitle.css({position: 'static', zIndex: 0});
            }

            if (scrollTop >= subTabTitleOffset.top &&
                scrollTop <= subTabTitleOffset.top + consult.height() - subTabTitle.height()) {

                subTabTitleClone.show();
                subTabTitle.css('z-index', 110);
                fix(subTabTitle, {top: 0});

            } else {
                subTabTitleClone.hide();
                subTabTitle.css({position: 'static', zIndex: 0});
            }

        });

        $(window).trigger('scroll');
        */
        // TabTitle项事件处理：定位、加载

        $('.strong-comm-count').click(function () {
            mainTabTitle.find('.li-tab').eq(3).trigger('click');
            window.scrollTo(0, mainTabTitleInitVal);
        });

        mainTabTitle.find('.li-tab').click(function () {
            window.scrollTo(0, mainTabTitleInitVal);
        });

        subTabTitle.find('.li-tab').click(function () {
            $(this).siblings().removeClass('li-now')
                .end().addClass('li-now');
            subTabTitle.css('position') == 'fixed' ?
                window.scrollTo(0, subTabTitleClone.offset().top) :
                window.scrollTo(0, subTabTitle.offset().top);
            consult.load($(this).attr('ajaxurl'));
            return false;
        });

        consult.on('click', '.p_page a', function (event) {
            consult.load($(event.target).attr('href'));
            subTabTitle.css('position') == 'fixed' ?
                window.scrollTo(0, subTabTitleClone.offset().top) :
                window.scrollTo(0, subTabTitle.offset().top);
            return false;
        });

    },


    _stockMessage: function () {//到货通知

        var stockedName = $('#stockedName'), stockedMail = $('#stockedMail'),

            stockedMobile = $('#stockedMobile'), stockTip = $('#form-stockeNotice .p-messageTip');

        var stockPop = null;


        $('#stockedNotice').on('click', function (event) {

            event.preventDefault();
            if ($(".user-has-logged").length) {

                stockPop = $.sobox.pop({

                    type: 'target',

                    cls: 'sopop-stockeNotice',

                    title: '到货通知',

                    target: '.ajax-stockeNotice'

                });

                return false;

            } else {

                ajaxLogin();

                return false;
            }
        });

        $('.ajax-stockeNotice .a-btn').click(function () {

            //var a = stockedName.val(),b = stockedMail.val(),c = stockedMobile.val(),d =$('#stockProductId').val();

            var c = stockedMobile.val(), d = $('#stockProductId').val();

            //if (a=='') {stockTip.text('对不起，请填写您的姓名！');return false;}

            //if (b==''||!(/^[a-zA-Z0-9_+.-]+\@([a-zA-Z0-9-]+\.)+[a-zA-Z0-9]{2,4}$/.test(b))) {stockTip.text('请填写正确格式的Email！');return false;}

            if (c == '' || !(/^1[3|4|5|8][0-9]\d{8}$/.test(c))) {
                stockTip.text('请填写正确的手机号码！');
                return false;
            }

            var $form = $("#form-stockeNotice");
            var url = $form.attr("action") + '?r=' + Number(new Date());
            var CSRFToken = $form.find("input[name='CSRFToken']").val();
            var CSRFMemKey = $form.find("input[name='CSRFMemKey']").val();

            $.post(url, {

                //'stockedName': a,

                //'stockedMail': b,

                'stockedMobile': c,

                'productId': d,

                'CSRFToken': CSRFToken,

                'CSRFMemKey': CSRFMemKey

            }, function (data) {

                //console.log(data);

                //console.log(typeof(data)=='object');

                $form.find("input[name='CSRFToken']").val(data.csrfToken);

                if (data.success) {

                    //stockedName.val('');stockedMail.val('');stockedMobile.val('');stockTip.text('');

                    stockTip.text('');
                    stockPop.removePop();
                    var originMobile = $('#ajax-stockeNotice-mobile');
                    if (originMobile.val()) {
                        stockedMobile.val(originMobile.val());
                    } else {
                        originMobile.val(stockedMobile.val());
                    }
                    //$("#ajax-stockeNotice-sended").val(1);//已经发送

                    $.sobox.alert('您的资料已提交成功！', '到货后，我们会第一时间通知您！感谢您关注海尔产品！');


                } else {

                    stockTip.text(data.message);

                    //	alert(data.message);

                }

            });


            return false;

        });

    },

    _groupProScrollEvent: function () {//套装滚动

        if ($(".group-scrollbox").length) {

            $(".group-scrollbox").each(function () {

                var _root = $(this);

                var group_list = _root.find(".group-list");

                var g_prev = _root.find(".g-prev");

                var g_next = _root.find(".g-next");

                var group_item = _root.find(".group-item");

                var group_count = group_item.length - 1;

                var index_g = 0;

                var left_g = 0;

                var width_g = 0;

                group_item.each(function () {

                    width_g += $(this).width() + 30;

                })

                if (width_g > 920) {

                    g_next.addClass("g-next-active");

                    g_next.click(function () {

                        if (index_g >= group_count) {

                            g_next.removeClass("g-next-active");

                        }

                        else {

                            left_g += group_item.eq(index_g).width() + 30;

                            index_g += 1;

                            g_prev.addClass("g-prev-active");

                            if (index_g >= group_count) {

                                g_next.removeClass("g-next-active");

                            }

                        }

                        group_list.animate({'left': -left_g}, "slow");

                    });

                    g_prev.click(function () {

                        if (index_g <= 0) {

                            g_prev.removeClass("g-prev-active");

                            left_g = 0;

                        }

                        else {

                            index_g -= 1;

                            left_g -= group_item.eq(index_g).width() + 30;

                            g_next.addClass("g-next-active");

                            if (index_g <= 0) {

                                g_prev.removeClass("g-prev-active");

                            }

                        }

                        group_list.animate({'left': -left_g}, "slow");

                    });

                }

            })

        }

    },

    js_tz_sc_toCart: function (parm) {

        var ajaxUrl = $(parm.obj).attr('href') || parm.ajaxUrl;


        $.get(ehaier.domainUrl.memberDomain + "/activity/userinit").done(function (result) {
            // 如果已经登录则继续
            if (result.success && result.data.memberId) {
                var ajaxPop = $.sobox.pop({

                    type: 'ajax',

                    cls: 'ajax-popInfoBox',

                    visibility: false,

                    ajax: {url: ajaxUrl, callback: function () {

                        if ($('#ajaxLoginForm').length) {

                            $('.ajax-popInfoBox .h2-sopop .s-title').text('用户登录');

                            //$('.ajax-popInfoBox').css({height:'390px'});

                            //setTimeout(function () {

                            $('.ajax-popInfoBox').css('visibility', 'visible').hide().fadeIn('fast');

                            //},20);

                        } else {

                            if ($(parm.popTitle).length) {

                                //if (parm.css) {$('.ajax-popInfoBox').css(parm.css);}

                                $('.ajax-popInfoBox .h2-sopop .s-title').text($(parm.popTitle).text());

                                $(parm.popTitle).remove();

                            }

                            $('.ajax-popInfoBox').css('visibility', 'visible');

                        }

                    }}

                });

                $('body').data('ajaxPop', ajaxPop);
            } else { // 否则先登录
                ajaxLogin();
            }

        });

    },

    galleryPreview: function () {

        //details-preview

        var page = 1;
        var $ul = $(".ul-gallery-thumb"), $li = $(".ul-gallery-thumb .li-thumb");
        var $liL = $li.length;
        var $bigShowBox = $(".gallery-showBox");
        var prevBtn = $('.gallery-thumbbox .b-prev'), nextBtn = $('.gallery-thumbbox .b-next');
        var firstBig = $li.find("a").attr("href");
        var str = '<div class="zoomplepopup"></div><div id="probig-preview" ><img class="img-preview" width="1024" height="1024" src="' + firstBig + '" alt="" /></div>';
        $bigShowBox.append(str);
        var $pre = $("#probig-preview");
        var $preimg = $(".img-preview");
        var $zoom = $bigShowBox.find(".zoomplepopup");
        var $SPage = Math.ceil($liL / 5), sLong = $li.width() * 5;
        var setmouse;

        function btnStyle() {
            if (page == 1) {
                prevBtn.removeClass('b-prev-active');
            } else {
                prevBtn.addClass('b-prev-active');
            }
            ;
            if (page == $SPage) {
                nextBtn.removeClass('b-next-active');
            } else {
                nextBtn.addClass('b-next-active');
            }
        };
        btnStyle();
        prevBtn.click(function () {
            if (page > 1) {
                page--;
                $(".ul-gallery-thumb").animate({left: "+=" + sLong})
            }
            ;
            btnStyle();
            return false;
        });
        nextBtn.click(function () {
            if (page < $SPage) {
                page++;
                $(".ul-gallery-thumb").animate({left: "-=" + sLong})
            }
            ;
            btnStyle();
            return false;
        });
        $li.mouseover(function () {
            var $this = $(this);
            setmouse = setTimeout(function () {
                $li.removeClass('li-now');
                $this.addClass('li-now');
                $preimg.attr("src", ($this.find("a").attr("href")));
                $(".img-bigshow").attr("src", $this.find("img").attr("longdesc"));
            }, 200);
        }).mouseout(function () {
            clearTimeout(setmouse);
        }).click(function () {
            return false;
        });
        var zoompos = {x: 0, y: 0};
        var p_w = $preimg.width();
        var p_h = $preimg.height();
        $bigShowBox.bind("mouseenter", function (g) {
            $pre.css({visibility: "visible"});
            var f = $(this);
            var a = $(this).width(), c = $(this).height();
            var b = $pre.width(), d = $pre.height();
            $zoom.width(b * a / p_w).height(d * c / p_h).show();
            PositionPopupZoom(f, $zoom, g.pageX, g.pageY, p_w, p_h);
            f.bind("mousemove", function (h) {
                setTimeout(function () {
                    PositionPopupZoom(f, $zoom, h.pageX, h.pageY, p_w, p_h)
                }, 2);
            });
        }).bind("mouseleave", function () {
            var a = $(this);
            $zoom.hide();
            $pre.css({visibility: "hidden"});
        });
        function PositionPopupZoom(a, o, m, k, n, f) {
            var c = a.offset().left;
            var i = a.offset().top;
            var d = o.width();
            var e = o.height();
            var l = a.width();
            var j = a.height();
            zoompos.x = m - c - (d / 2);
            zoompos.y = k - i - (e / 2);
            if (zoompos.x <= 0) {
                zoompos.x = 0
            }
            ;
            if (zoompos.y <= 0) {
                zoompos.y = 0
            }
            ;
            if (zoompos.x + d >= l) {
                zoompos.x = l - d
            }
            ;
            if (zoompos.y + e >= j) {
                zoompos.y = j - e
            }
            ;
            var b = n / l;
            var g = f / j;
            o.css({left: zoompos.x, top: zoompos.y});
            $preimg.css({left: -(zoompos.x * b), top: -(zoompos.y * g)})
        }

    },

    _popShowGallery: function () {

        /*$('.a-view-gallery').click(function () {

            $.sobox.pop({width: 635, height: 520, type: 'target', target: '.gallery-popBox', title: $('.product-title .s-title').text()});

            return false;

        });*/

        var now = 0, $ul = $('.pop-gallery-thumb'), $li = $('.pop-gallery-thumb li'), liLen = $li.length,

            popImgA = $('.pop-gallery-bigshow .a-bigshow'), popImg = popImgA.find('img');

        popImgA.attr('href', $li.find('a').attr('href'));

        $li.click(function () {

            var indx = $li.index(this);

            now = indx;

            $li.removeClass('li-now');

            $(this).addClass('li-now');

            var bigSrc = $(this).find('img').attr('longdesc'), bigSrcA = $(this).find('a').attr('href');

            popImg.attr('src', bigSrc);
            popImgA.attr('href', bigSrcA);

            return false;

        });

        $('.pop-gallery-bigshow .b-next').click(function () {

            now = (now + 1) * 1 % liLen;

            if (now < (liLen - 4)) {
                $ul.animate({'left': -65 * now});
            }

            $li.eq(now).trigger('click');

        }).hoverClass('b-next-active');

        $('.pop-gallery-bigshow .b-prev').click(function () {

            now = (now + liLen - 1) * 1 % liLen;

            if (liLen > 5) {
                if (now > (liLen - 5)) {
                    $ul.animate({'left': -65 * (liLen - 5)});
                } else {
                    $ul.animate({'left': -65 * now});
                }
            }

            $li.eq(now).trigger('click');

        }).hoverClass('b-prev-active');

    },

    _popGallery: function () {

        var $aThumb = $('.ul-gallery-thumb .a-thumb'), urlArr = [];

        var nowIx = 0;

        var wh, imgH, btnT;


        $aThumb.each(function () {

            urlArr.push(this.getAttribute('href'));

        });

        var urlL = urlArr.length;

        $('body').append('<p class="p-gallery-show-btn"><span class="s-btn-gallery s-gallery-prev"></span><span class="s-btn-gallery s-gallery-next"></span></p>');

        var $pBtn = $('.p-gallery-show-btn');

        $('.a-view-gallery').click(function (e) {
        	e.preventDefault();

            nowIx = $('.ul-gallery-thumb li').index($('.ul-gallery-thumb li.li-now')) || nowIx;

            wh = $(window).height();

            wh = wh < 1240 ? wh : 1240;

            imgH = wh - 40;

            $pBtn.fadeIn();

            $.sobox.pop({

                cls: 'pop-lightbox',

                width: (wh + 30), height: (wh - 35),

                offset: [0, 8],

                showTitle: false,

                content: '<img id="img-lightbox" width="' + imgH + '" height="' + imgH + '" src="' + urlArr[nowIx] + '" alt="" /><span id="span-gallery-page"><em class="em-page-now">' + (nowIx * 1 + 1) + '</em> / <em class="em-page-all">' + urlL + '</em></span><span class="s-loading"><img width="35" height="35" alt="" src="' + itemDomain +  '/shoppingmall_item/resources/images/loading.gif"></span>',

                closePop: function () {

                    $pBtn.hide();

                }

            });

            return false;

        });

        $('.p-gallery-show-btn .s-gallery-next').click(function () {

            nowIx = (nowIx + 1) % urlL;

            changeFunc(nowIx);

        });

        $('.p-gallery-show-btn .s-gallery-prev').click(function () {

            nowIx = (nowIx + urlL - 1) % urlL;

            changeFunc(nowIx);

        });

        function changeFunc(nowIx) {

            var $img = $('<img src="' + urlArr[nowIx] + '" alt="" />');

            $('.pop-lightbox .s-loading').show();

            $img.load(function () {

                $('#img-lightbox').hide().attr('src', urlArr[nowIx]).fadeIn();

                $('.s-loading').hide();

                $('.em-page-now').html(nowIx * 1 + 1);

            });

            $img = null;

        }

        $(window).resize(function () {//window size变化重置

            if ($('#img-lightbox').length) {

                wh = $(window).height();

                var dh = $(document).height() + 10;

                wh = wh < 1240 ? wh : 1240;

                imgH = wh - 40;

                $('#img-lightbox').css({'width': imgH, 'height': imgH});

                $('.pop-lightbox').css({'width': (wh + 30), 'height': (wh - 35), 'marginTop': (-(wh - 30) / 2), 'marginLeft': (-(wh + 30) / 2)});

                $('.so-openmask').height(dh);

            }

        });

    }

}


$(function () {

    ehaier.product.init();//product js init
});


$(function () {

    /* 购物地区切换及购买 */

    (function () {

        var $_root = $('.product-info');

        var $_rootTop = $('.crumb').position().top;

        var js_pid = $_root.find('.js_pid').val();

        var js_acid = $_root.find('.js_acid').val();

      //  var reigonUrl = ehaier.domainUrl.baseDomain + "/outRegionJson?pid=" + js_pid + '&acid=' + js_acid;
        var reigonUrl = "http://www.rrs.com/outRegionJson?pid=19331&acid=0";

        var api_change_region = '/region.php?a=selectRegion';

        var reigonData = {};


        //初始化加载地区和所有相关商品delivery信息

        $.ajax(reigonUrl, {

            dataType: 'jsonp',

            success: function (data) {

                reigonData = data.data;

                deliveryEvent(data.data);

            }

        });


        $('#buyActive').on('click', function () {//集合竞价提交按钮事件  **直接清空创客购物车

            if (check_region()) {

                var acid = $("input[name='acid']").val();

                var num = $("input[name='num']").val();

                var canSaleFlag = $("input[name='canSaleFlag']").val();

                var cookieValue = "acid:" + acid + "_num:" + num + "_canSaleFlag:" + canSaleFlag;

                //$.cookie.raw = true;

                $.cookie("ORDER_SHOW_JHJJ_PARAM", cookieValue, { path: '/', domain: ehaier.domainUrl.cookieDomain });


                var fe_data = $_root.get_fe_data();

                $.ajax({

                    url: '/order/isShowSettlement?source=product',

                    dataType: 'json',

                    data: fe_data,

                    success: function (data) {

                        if (data.success) {

                            //$('#buyForm').submit();
                            // 清空创客购物车

                            window.location.href = "/order.html?source=product";

                        } else {

                            if (data.data == 0) {

                                window.location.href = '/';

                            } else {

                                $.sobox.alert('提示', data.message);

                            }

                        }

                    }

                });

                return false;

            } else {
                return false;
            }

        });


        $('.js_tz_toCart').on('click', function () {//组合销售 **直接清空创客购物车

            var pid = $(this).attr('pid');

            gotoCart(this, {pid: pid, allowNum: false});//销售数量只能为1

            return false;

        });

        $('.js_tz_sc_toCart').on('click', function () {//套系销售

            var pid = $(this).attr('pid');

            gotoCart(this, {pid: pid, allowNum: true});//销售数量可更改

            return false;

        });

        //加入购物车（加入购物车后跳出弹出层）
        if (!$("#buyIt").attr("alreadyExists")) {
            $('#buynow').on('click', function () {
                doBuyNow();
            });
            $('#buyIt').on('click', function () {
                addToCart(this);
            });
            $("#buyIt").attr("alreadyExists","true")
        }

        function deliveryEvent(data) {

            var $province = $_root.find('.js_fe_province'), $city = $_root.find('.js_fe_city'), $region = $_root.find('.js_fe_region');

            var $jieneng = $_root.find('.js_jieneng'), $isSupportCod = $_root.find('.isSupportCod');

            var js_pid = $_root.find('.js_pid').val(), js_acid = $_root.find('.js_acid').val();


            var $btn_buy_now = $_root.find('.js_buy_now');

            var $btn_add_to_cart = $_root.find('.js_add_to_cart');

            var $deliver_box = $_root.find('.deliverybox');

            var $header_curCity = $('.js-choose-city');

            var $header_curCity_name = '';


            //show and hide

            $('.p-delivery .s-location').mouseover(function () {

                $('.sel-location-box').show();

            });

            $('.fe_region').click(function () {

                $('.sel-location-box').hide();

            });

            $('.deliverybox').mouseleave(function () {

                $('.sel-location-box').hide();

            });

            if (!$("#buyIt").attr("alreadyExists")) {
                $('#buynow').on('click', function () {
                    doBuyNow();
                });
                $('#buyIt').on('click', function () {
                    addToCart(this);
                });
                $("#buyIt").attr("alreadyExists","true")
            }
            
            


            //s-pro-num

            var $txtNum = $('.s-pro-num .txt-num');

            $('.s-pro-num .em-sub').click(function () {

                var nv = parseInt($txtNum.val());

                $txtNum.val(nv > minBuyNum ? (nv * 1 - 1) : minBuyNum);
                
                getLadderPrice($txtNum.val());
                
                sumCustomizeNumAndPrice();//计算搭配套餐总价格
            });

            $('.s-pro-num .em-add').click(function () {

                var nv = $txtNum.val();

                $txtNum.val(nv * 1 + 1);
                
                getLadderPrice($txtNum.val());
                
                sumCustomizeNumAndPrice();//计算搭配套餐总价格
            });


            var linV = 1;

            $txtNum.focus(function () {

                linV = this.value;

            }).blur(function () {

                var v = this.value;

                if (!/^[1-9]\d*$/.test(v)) {

                    $.sobox.alert('提示', '购买件数必须为正整数，请正确输入！');

                    $(this).val(linV);
                    
                    getLadderPrice($txtNum.val());

                }else{
                	if (parseInt(v) < minBuyNum){
                		$.sobox.alert('提示','购买件数不能小于最小购买数量 ' + minBuyNum);
                		$(this).val(minBuyNum);
                	}
                	
                	getLadderPrice($(this).val());
                }

            });


            //function init_region_selector (data) {


            var province_da = [];

            var city_da = [];

            var region_da = [];

            for (var i = 0; i < data.length; i++) {

                var cur_province = data[i];

                province_da.push({

                    'id': cur_province.id,

                    'name': cur_province.name

                });


                for (var j = 0; j < cur_province.children.length; j++) {

                    var cur_city = cur_province.children[j];

                    city_da.push({

                        'id': cur_city.id,

                        'name': cur_city.name,

                        'fid': cur_province.id

                    });


                    for (var k = 0; k < cur_city.children.length; k++) {

                        var cur_region = cur_city.children[k];

                        region_da.push({

                            'id': cur_region.id,

                            'name': cur_region.name,

                            'fid': cur_city.id

                            //'url':cur_region.url

                        });

                    }

                }

            }


            //省绑定change事件


            $province.change(function () {

                var $this_sel = $(this);

                var cur_val = $this_sel.val();

                var cityHtml = '<option value="">- 请选择 -</option>';


                for (var i = 0; i < city_da.length; i++) {

                    if (city_da[i].fid == cur_val) {

                        cityHtml += '<option value="' + city_da[i].id + '">' + city_da[i].name + '</option>';

                    }

                }

                $city.html(cityHtml);

                $city.val('').change();

                $region.val('').change();

                $city.attr('disabled', (cur_val ? false : true));

                $region.attr('disabled', true);


            });


            //城市绑定change事件

            $city.change(function () {

                var $this_sel = $(this);

                var cur_val = $this_sel.val();

                for (var i = 0; i < city_da.length; i++) {

                    if (city_da[i].id == cur_val) {

                        $header_curCity_name = city_da[i].name;

                        break;

                    }

                }

                //$region.empty();

                var regionHtml = '<option value="">- 请选择 -</option>';

                for (var i = 0; i < region_da.length; i++) {

                    if (region_da[i].fid == cur_val) {

                        regionHtml += '<option value="' + region_da[i].id + '">' + region_da[i].name + '</option>';

                    }

                }

                $region.html(regionHtml);

                $region.val('').change().attr('disabled', (cur_val ? false : true));

                //获取库存信息和价格
                var prodId = ehaier.domainUrl.productId;
                var cityId = cur_val;
                if (cityId){
                	var url = itemDomain + "/product/ajaxinfo.html";
                	$.ajax(url,{
                		type: "get",
                		cache: false,
                		data: "productId=" + prodId + "&cityId=" + cityId +  "&" +getCSRFTokenParam() + "&tmp=" + getRandomStr() ,
                		success: function(data){
                			var marketItemUrl = ehaier.domainUrl.itemDomain + "/product/" + prodId + ".html";
                			if (data.data.data.singlePrice == "1"){
                				$(".cur-price").html('￥' + data.data.data.productPrice);
                				basePrice = data.data.data.productPrice;
                			}
                            //add by 365rrs价格显示修改 begin
                            else if (data.data.data.singlePrice == "2"){
                                $(".cur-price").html('￥' + data.data.data.realProductPrice);
                                basePrice = data.data.data.realProductPrice;
                                $(".cur-price").prev().html(data.data.data.memberTypeDisplayName + "价：");
                                if ($(".cur-price").parent().find("span[id='jsMinNum']").length > 0){
                                    $("#jsMinNum").html(" （"+ data.data.data.b2bPriceInfo + "）");
                			    }else{
                                    $("<span id='jsMinNum'> （"+ data.data.data.b2bPriceInfo + "）</span>").insertAfter(".cur-price");
                                }
                                if ($(".cur-price").parent().parent().find("li[id='jsMallPrice']").length > 0){
                                    $("#jsMallPrice").html("<span class='s-title'>建议零售价：</span><strong class='haierred no-price'>￥" + data.data.data.productPrice + "</strong>");
                                }else{
                                    $("<li id='jsMallPrice'><span class='s-title'>建议零售价：</span><strong class='haierred no-price'>￥" + data.data.data.productPrice + "</strong></li>").insertBefore($(".cur-price").parent());
                                }
                                $("#buyNum").val(minBuyNum);
                            }
                            //add by 365rrs价格显示修改 end
                            //全额预售 20160318 begin
                            else if (data.data.data.singlePrice == "3"){
                                $(".cur-price").html('￥' + data.data.data.realProductPrice);
                                basePrice = data.data.data.realProductPrice;
                                $(".cur-price").prev().html(data.data.data.memberTypeDisplayName + " 价：");

                                if ($(".cur-price").parent().parent().find("li[id='jsMallPrice']").length > 0){
                                    $("#jsMallPrice").html("<span class='s-title'>商 城 价：</span><strong class='haierred no-price'>￥" + data.data.data.productPrice + "</strong>");
                                }else{
                                    $("<li id='jsMallPrice'><span class='s-title'>商 城 价：</span><strong class='haierred no-price'>￥" + data.data.data.productPrice + "</strong></li>").insertBefore($(".cur-price").parent());
                                }
                                //minBuyNum = data.data.data.minBuyNumber;
                                $("#buyNum").val(minBuyNum);
                            }
                            //全额预售 20160318 end
                			//限时抢购/秒杀 20160520 begin
                            else if (data.data.data.singlePrice == "4" ){
                            	if( data.data.data.flashSale_status=='2' ){
                            		$(".cur-price").html('￥' + data.data.data.realProductPrice);
                            		$(".cur-price").prev().html(data.data.data.memberTypeDisplayName + " 价：");
                            		
                            		basePrice = data.data.data.realProductPrice;
                            		if ($(".cur-price").parent().parent().find("li[id='jsMallPrice']").length > 0){
                            			$("#jsMallPrice").html("<span class='s-title'>商 城 价：</span><strong class='haierred no-price'>￥" + data.data.data.productPrice + "</strong>");
                            		}else{
                            			$("<li id='jsMallPrice'><span class='s-title'>商 城 价：</span><strong class='haierred no-price'>￥" + data.data.data.productPrice + "</strong></li>").insertBefore($(".cur-price").parent());
                            		}
                            		$("#buyNum").val(minBuyNum);
                            	}else{//活动未开始
                            		$(".cur-price").html('<span style="color:grey;font-weight:normal">￥' + data.data.data.realProductPrice+'</span><span style="display: inline-block;padding: 0px 4px; border: 1px dotted #c7003a;line-height: 17px;color: #c7003a;font-weight: normal;font-size: 12px;margin-left: 16px;">暂未开始</span>');
                            		$(".cur-price").prev().html(data.data.data.memberTypeDisplayName + " 价：");
                            		basePrice = data.data.data.realProductPrice;
                            		$(".cur-price").removeClass('haierred');
                            		
                            		if ($(".cur-price").parent().parent().find("li[id='jsMallPrice']").length > 0){
                            			$("#jsMallPrice").html("<span class='s-title'>商 城 价：</span><strong class='haierred cur-price'>￥" + data.data.data.productPrice + "</strong>");
                            		}else{
                            			$("<li id='jsMallPrice'><span class='s-title'>商 城 价：</span><strong class='haierred cur-price'>￥" + data.data.data.productPrice + "</strong></li>").insertBefore($(".cur-price").parent());
                            		}
                            		$("#buyNum").val(minBuyNum);
                            	}
                            }
                            //限时抢购/秒杀 end
                            else{
                				$(".cur-price").html('￥' + data.data.data.realProductPrice);
                				basePrice = data.data.data.realProductPrice;
                				$(".cur-price").prev().html(data.data.data.memberTypeDisplayName + " 价：");
                				if ($(".cur-price").parent().find("span[id='jsMinNum']").length > 0){
                					$("#jsMinNum").html(" （最少起购数："+ data.data.data.minBuyNumber + "）");
                				}else{
                					$("<span id='jsMinNum'> （最少起购数："+ data.data.data.minBuyNumber + "）</span>").insertAfter(".cur-price");
                				}
                				if ($(".cur-price").parent().parent().find("li[id='jsMallPrice']").length > 0){
                					$("#jsMallPrice").html("<span class='s-title'>商 城 价：</span><strong class='haierred no-price'>￥" + data.data.data.productPrice + "</strong>");
                				}else{
                					$("<li id='jsMallPrice'><span class='s-title'>商 城 价：</span><strong class='haierred no-price'>￥" + data.data.data.productPrice + "</strong></li>").insertBefore($(".cur-price").parent());
                				}
                				minBuyNum = data.data.data.minBuyNumber;
                				$("#buyNum").val(minBuyNum);
                			}
                			if (data.data.data.stock > 0){
                				if (firstEnterPage == 1){                					
                					mvqFunction(1,marketItemUrl);
                				}
                				//$(".p-product-btn").html(buyBtnHtml); // 搭配套餐部分修改 默认显示立即购买
                				var l_span = $('.l-package-span');
                				if( l_span.length>0 ){ //判断是否存在搭配套餐
	                				if( isMainProStock ){
	                	            	$(".p-product-btn").html(buyAddOrderBtnHtml);
	                	            	$('#custmizebuyIt').on('click', function () {
	                                        addToCustomizeOrder(this);
	                                    });
	                	            }
                				}else{
                					$(".p-product-btn").html(buyBtnHtml);
                				}
                                //365RRS 我要预定
                                if (data.data.data.singlePrice == "2"){
                                    $(".p-product-btn").append(predetermineHtml);
                                }
                				$(".deliver-tip").html("有货，免费配送");
                				var itemSource = $("input[name='productItemSource']").val();
                				if (itemSource == '0'){
                					if ($(".deliverybox").find("p[id='jsInvoiceInfoHtml']").length > 0){
                					}else{
                						$(".p-product-btn").after(invoiceInfoHtml);
                					}
                					if(data.data.data.saleType=='0'){
                						if (data.data.data.shippingTime){
                							$(".deliver-tip").append("，预计" + data.data.data.shippingTime +"天送达");
                						}
                					}
                				}else{
                					$(".deliver-tip").html("，以第三方物流配送时间为准");
                				}
                				if (!$("#buyIt").attr("alreadyExists")) {
                                    $('#buynow').on('click', function () {
                                        doBuyNow();
                                    });
                		            $('#buyIt').on('click', function () {
                		                addToCart(this);
                		            });
                		            $("#buyIt").attr("alreadyExists","true")
                		        }
                                //预售抢购 20160318 begin
                                if (data.data.data.singlePrice == "3"){
                                    $(".p-product-btn").html(presaleHtml);
                                    if(data.data.data.presaleEnd == "1"){
                                        $(".p-product-btn").html(presaleStopHtml);
                                    }
                                    $(".deliver-tip").html("");
                                }
                                //预售抢购 20160318 end
                                //限时抢购/秒杀 20160520 begin
                                if (data.data.data.singlePrice == "4" && data.data.data.flashSale_status=="2"){
                                    $(".p-product-btn").html(flashSaleHtml);
                                    flashSaleButten = 1;
                                }
                                //限时抢购/秒杀 20160520 end
                                //搭配套餐
                                isMainProStock = true;
                                //搭配套餐
                			}else{   
                				if (firstEnterPage == 1){
                					mvqFunction(0,marketItemUrl);
                				}
                				$(".p-product-btn").html(noStockHtml);
                                //365RRS 我要预定
                                if (data.data.data.singlePrice == "2"){
                                    $(".p-product-btn").append(predetermineHtml);
                                }
                				$(".deliver-tip").html("该地区无货");
                                //预售抢购 20610316 begin
                                if (data.data.data.singlePrice == "3"){
                                    $(".p-product-btn").html(presaleHtml);
                                    if(data.data.data.presaleEnd == "1"){
                                        $(".p-product-btn").html(presaleStopHtml);
                                    }
                                    $(".deliver-tip").html("");
                                }
                                //预售抢购 20610316 end
                                //搭配套餐
                                isMainProStock = false;
                                //搭配套餐
                			}                			
                			refrushCSRFToken(data.csrfToken);
                			if ($("#jsPromotion")){
                				$("#jsPromotion").remove();
                			}
                			showPromotionInfo();
                			ladderPrices = [];
                		},
                		exception: function(data){
                			$(".cur-price").html('暂时无法获取价格信息，请刷新本页面！');
                			refrushCSRFToken(data.csrfToken);
                		}
                	});
                }
            });


            //地区绑定change事件

            $region.change(function () {

                var $this_sel = $(this);

                var regionid = $this_sel.val();

                for (var i = 0; i < region_da.length; i++) {

                    if (region_da[i].id == regionid) {

                        var proId = ehaier.domainUrl.productId;

                        var actid = ehaier.domainUrl.actId;

                        var preview = ehaier.domainUrl.preview;

                        var url = memberDomain + '/changeRegionJson?id=' + proId + '&regionId=' + regionid;

                        $.ajax(url, {

                            dataType: 'jsonp',

                            cache: false,

                            success: function (data) {

                                if (data.success) {

                                    var proLoadUrl = '/product/changeregion/prodinfo?productId=' + proId + '&regionId=' + regionid + '&actId=' + actid + '&preview=' + preview;

                                    var packageUrl = '/product/changeregion/packageinfo?productId=' + proId + '&regionId=' + regionid;

                                    $.ajax(proLoadUrl, {

                                        cache: false,

                                        dataType: 'html',

                                        success: function (htmlData) {

                                            if (htmlData == '') {                                            	
                                                window.location.href = ehaier.domainUrl.commonErrorPageUrl;

                                            } else {

                                                $(".product-info").html(htmlData);

                                                deliveryEvent(reigonData);

                                                $header_curCity.html($header_curCity_name);

                                                ehaier.product._sharePro();//share

                                                $('.js-cart-num').html('0');


                                                //ga track

                                                var stock = {state: null, mes: null};

                                                if ($('.p-product-btn').find('#buy_Now').length > 0) {

                                                    stock.state = 1;

                                                    stock.mes = '有货';

                                                }

                                                if ($('.p-product-btn').find('#stockedNotice').length > 0) {

                                                    stock.state = 2;

                                                    stock.mes = '到货通知';

                                                }

                                                if ($('.p-product-btn').find('#nostock').length > 0) {

                                                    stock.state = 3;

                                                    stock.mes = '无货';

                                                }

                                                var proTitle = $('.product-title').text();

                                                var location = $('.s-location').html();

                                                var trackData = proTitle + '-' + location + '-' + stock.mes;

                                                _gaq.push(['_trackEvent', 'proRegion', trackData, proTitle, stock.state]);

                                                _gaq.push(['_trackEvent', 'regionStock', location, stock.mes, stock.state]);

                                                _gaq.push(['_trackPageview', ('/trackUrl/product/region-' + trackData)]);

                                            }

                                        }



                                    });

                                    /*$.ajax(packageUrl, {

                                        cache: false,

                                        dataType: 'html',

                                        success: function (htmlData) {

                                            $("#packageGroups").html(htmlData);

                                            ehaier.product._groupProScrollEvent();

                                        }

                                    });*/

                                } else {

                                    $.sobox.alert('提示', data.message);

                                }

                            }

                        });
                        break;

                    }

                }


            });


            //初始化数据项


            var default_id_province = parseInt($province.data('default_id')) || '';//获得省

            var default_id_city = parseInt($city.data('default_id')) || '';//获得市

            var default_id_region = parseInt($region.data('default_id')) || '';//获得区

            $province.empty();

            var provinceHtrml = '<option value="">- 请选择 -</option>';

            for (var i = 0; i < province_da.length; i++) {

                provinceHtrml += '<option value="' + province_da[i].id + '">' + province_da[i].name + '</option>';

            }

            if (default_id_city != '') {//切换地区时省id有缓存，暂无法解决，通过市id返回查找省id

                for (var i = 0; i < city_da.length; i++) {

                    if (city_da[i].id == default_id_city) {

                        default_id_province = city_da[i].fid;

                        break;

                    }

                }
                ;

            }


            $province.append(provinceHtrml);

            $province.val(default_id_province).change();

            $city.val(default_id_city).change();

            $region.val(default_id_region);

            //搭配套餐部分开始 wshsh 20160429
            $('.l-package').click(function(){
                if($('input[name="l-package"]').prop("checked")){
                    $(this).parent('.l-package-span').css('background-image', 'url(' + itemDomain +  '/shoppingmall_item/resources/images/product/p_package_s.jpg)');  
                    //显示搭配套餐层
                    $('#isShow_customize').hide();
                    //立即购买按钮
                    if( isMainProStock ){
                    	$(".p-product-btn").html(buyAddOrderBtnHtml);
                    }else{
                    	$(".p-product-btn").html(noStockHtml);
                    }
                    $('#custmizebuyIt').on('click', function () {
                        addToCustomizeOrder(this);
                    });
                    $('.l-package-box').css({'border':'1px dotted #c7003a'});
                }else{
                	$(this).parent('.l-package-span').css('background-image', 'url(' + itemDomain +  '/shoppingmall_item/resources/images/product/p_package_us.jpg)');
                	if( isMainProStock ){
                		$(".p-product-btn").html(buyBtnHtml);
                    }else{
                    	$(".p-product-btn").html(noStockHtml);
                    }
                    //加入购物车（加入购物车后跳出弹出层）
                    if ( !$("#buyIt").attr("alreadyExists") ) {
                        $('#buynow').on('click', function () {
                            doBuyNow();
                        });
                        $('#buyIt').on('click', function () {
                            addToCart(this);
                        });
                        $("#buyIt").attr("alreadyExists","true")
                    }
                    //隐藏搭配套餐层
                    $('#isShow_customize').show();
                    $('.l-package-box').css({'border':'0px'});
                }
            });
            
            $('.customize-pro-num .em-sub').click(function () {
                var value = $(this).parent().children().eq(1).attr('value');
            	if (Number(value) > 0 ) {
            		value = Number(value) - 1;
        			$(this).parent().children().eq(1).attr('value', value);
            	}
            	if (Number(value) == 0 ){
            		$(this).parent().parent().children().eq(0).css({
                		"display": "inline-block",
                		"width": "100%",
                		"border": 0
                	});
            	}
            	//选中时，更新组合套餐数量和价格
            	sumCustomizeNumAndPrice();
            });

            $('.customize-pro-num .em-add').click(function () {
            	var customizeStockNum = $(this).parent().children().eq(1).attr('customizeStockNum');
            	if( Number(customizeStockNum) == 0  ){
            		$.sobox.alert('提示', '该套餐搭配商品在该地区无货！');
            		return;
            	}
            	$(this).parent().parent().children().eq(0).css({
            		"display": "inline-block",
            		"width": "100%",
            		"border": "1px solid #c7003a"
            	});
            	var value = $(this).parent().children().eq(1).attr('value');
        		value = Number(value) + 1;
        		$(this).parent().children().eq(1).attr('value', value);
        		//选中时，更新组合套餐数量和价格
        		sumCustomizeNumAndPrice();
            });
            $("#buyNum").blur(function(){
            	//购买数量 失去焦点计算
        		sumCustomizeNumAndPrice();
            });
            //搭配套餐部分结束
        }


        //检查城区

        function check_region() {

            var $region = $_root.find('.js_fe_region');

            if (parseInt($region.val())) {

                return true;

            } else {

                $('.deliver-tip').addClass('red');

                $('.sel-location-box').fadeIn();

                return false;

            }

        }


        //检查节能

        function check_jieneng(_callback) {

            var $jieneng = $_root.find('.js_jieneng')

            if ($jieneng.val() > 0) {

                //$.sobox.show('.subsidy-box');

                $.sobox.pop({

                    cls: 'subsidy-box',

                    title: '节能补贴商品购买须知',

                    width: 480,

                    content: '<div><p style="text-align: left">该产品为节能型号，下单成功后请您及时准备节能补贴资料。</p><p style="text-align: left">海尔送装人员上门时，需要您的节能补贴资料才能为您开箱安装，届时请您主动提供身份证复印件（包含正、反面）或营业执照复印件，并在《节能产品惠民工程补贴确认函》上签字确认。如您证件信息不齐全或有误，我们将无法完成送装服务。详情请查看<a href="/helpcenter.php?id=29" target="_blank" style="color:red">节能补贴实施细则</a></p><p style="font-weight:bold; text-align: left">节能补贴的商品如需退款，我们只退还您交易中实际支付的金额，节能补贴的金额不予退还。</p></div>',

                    btn: [

                        {text: '不接受', cls: 'a-cancel'},

                        {text: '接受并购买', callback: function (_params) {

                            //if ( typeof _params == "function" ){_params();}

                            _callback();

                        }

                        }
                    ]

                });

                return false;

            } else {

                _callback();

            }

        }


        //加入购物车

        function add_to_cart(d, _callback) {

            var fe_data;

            if (d) {

                var num = d.allowNum ? ($('#buyNum').val() * 1) : 1;

                fe_data = {id: d.pid, num: num, type: 1, acid: 0, r: Math.random()};

            } else {
                fe_data = $_root.get_fe_data();

            }
            //ehaier.base.miniCart.add(fe_data,_callback);
            pdetailMinCart.add(fe_data, _callback);

            flag = false;

        }


        function gotoCart(o, d) {

            var $this = $(o);

            if (!$this.data('disable')) {

                add_to_cart(d, function (data) {

                    $('#buyNum').val(data.data.num);

                    if (data.success) {
                        if ($('#identifier').length) {
                            window.location.href = cartDomain + '/ckcart.html';
                        } else {
                            window.location.href = cartDomain + '/cart.html';
                        }
                    } else {

                        $.sobox.alert('提示', data.data.msg);

                        return false;

                    }

                });

            }

            return false;

        }


        function directGoCart(o, d) {

            var $this = $(o);

            if (!$this.data('disable')) {

                if (check_region()) {

                    add_to_cart(d, function (data) {

                        $('#buyNum').val(data.data.num);

                        if (data.success) {

                            //$('.js_buy_now').die('click', '**');

                            if ($('#identifier').length) {
                                window.location.href = cartDomain + '/ckcart.html';
                            } else {
                                window.location.href = cartDomain + '/cart.html';
                            }
                        } else {

                            $.sobox.alert('提示', data.data.msg);

                            return false;

                        }

                    });

                }

            }

            return false;

        }

        function addToCart(o, d) {

            var $this = $(o);

            if (!$this.data('disable')) {

                if (check_region()) {

//                    check_jieneng(function () {

                    add_to_cart(d, function (data) {

                        $('#buyNum').val(data.data.num);

                        if (data.success) {

                            $.sobox.pop({

                                cls: 'pop-successCart',

                                title: '加入购物车成功',

                                content: data.data.msg,

                                btn: [
                                    {text: '继续购物', cls: 'a-cancel'},
                                    {text: '去购物车结算', cls: 'a-tobuy', callback: function () {
                                        if ($('#identifier').length) {
                                            window.location.href = cartDomain + '/ckcart.html';
                                        } else {
                                            window.location.href = cartDomain + '/cart.html';
                                        }
                                    }}
                                ]

                            });
                        } else {

                            $.sobox.alert('出错了', data.data.msg);

                            return false;

                        }

//							if ( typeof data.message != undefined && data.message > 0 ){

//								$.sobox.alert('出错了',data.result);

//							}else{

//								$.sobox.pop({

//									cls:'pop-successCart',

//									title:'加入购物车成功',

//									content:data.result,

//									btn:[{text:'继续购物',cls:'a-cancel'},{text:'去购物车结算',callback:function () {

//										window.location.href='/cart.php';

//									}}]

//								});

//							}

                    });

//                    });

                }

            }

            return false;

        }

        // 执行普通立即购买
        function doBuyNow() {
            var that = this;
            if (check_region()) {
                $.ajax({
                    type: 'GET',
                    url: rrs.memberDomain + '/headLoginAjax',
                    dataType: 'jsonp',
                    jsonp: 'callback',
                    success: function (data) {
                        if (data.isLogin === false) {
                            var ajaxUrl = memberDomain + '/ajaxLogin?callback=?';
                            $.getJSON(ajaxUrl, function (data) {
                                var ajaxPop = $.sobox.pop({
                                    cls: 'ajax-popInfoBox',
                                    title: '用户登录',
                                    defaultShow: true,
                                    visibility: true,
                                    onlyOne: true,
                                    width: 340,
                                    content: data.data,
                                    async: false,
                                    callback: function () {
                                        $('.ajax-popInfoBox .h2-sopop .s-title').text('用户登录');
                                        $('.ajax-popInfoBox').css('visibility', 'visible').hide().fadeIn('fast');
                                    }
                                });
                               // ajaxPop.showPop();
                               // $('body').data('ajaxPop', ajaxPop);
                            });
                        } else {
                            // 遍历选择的商品
                            var orderObject=new OrderProdObject();
                            orderObject.activityId=2;//立即购买
                            var productId = $("#currentProductIdHidden").val();
                            var num = $("#buyNum").val();
                            var newProd=new ProdObject();
                            newProd.productId=Number(productId);
                            newProd.number=Number(num) ;
                            orderObject.products.push(newProd);
                            var strMsg = JSON.stringify(orderObject)
                            strMsg=encodeURI(strMsg);
                            $("#jsonProducts").val(strMsg);
                            $("#o2oform").submit();
                        }
                    },error: function () {
                        $.sobox.alert('提示','对不起，服务器异常!');
                        return false;
                    }
                });
            }
        }
    })();

});

(function() {
	
	
	$('#itemQuestionPopClose').click(function() {
		$('.so-popbox-mask').hide();
		$('.ajax-popInfoBox').hide();
	});	
	$('#itemArrivalPopClose').click(function() {
		$('.so-popbox-mask').hide();
		$('.ajax-arrival').hide();
	});
	
	
	
	/*$('.dpsource').hover(function() {
		var iTop = $(this).position().top;
		
		$('.shop-tips').css({
			'display': 'block',
			'top': iTop + $(this).height() + 10 + 'px'
		});
	}, function() {
		$('.shop-tips').css({
			'display': 'none'
		});
	});*/
	
	var productId = $("#currentProductIdHidden").val();
	//加上分享增加积分的链接
	$('.jsAddPoints').click(addPoints);
	
	//请求后台的库存信息，显示“加入购物车辆”或“暂时无货”
	
	
	function addPoints(){
		try {
	        var mid = ehaier.domainUrl.uid;
	    } catch (e) {
	        ajaxLogin();
	        return false;
	    }

	    if (mid == '' || mid == 0) {
	        ajaxLogin();
	        return false;
	    }
		
		
		$.ajax({
	        type : "post",
	        url : itemDomain + "/product/point/shareAddPoint.html",
	        data: "productId=" + productId +  "&" +getCSRFTokenParam(),
	        contentType: "application/x-www-form-urlencoded; charset=utf-8", 
	        success : function(data){
	        	refrushCSRFToken(data.csrfToken);
	        },
	        error:function(){	        	
	        	$.sobox.alert('提示', '抱歉，您的分享未能增加积分，请稍后再试！');
	            refrushCSRFToken(data.csrfToken);
	            return false;
	        }
	    });	
	}
	
	//dpsource
	if (!$('.dpsource').length) {
		return false;
	}
})();

function getRandomStr(){
	return new Date().getTime() + "" + Math.floor(Math.random()*1000+1);
}

function mvqFunction(stock, marketItemUrl){
	var _mvq = window._mvq || []; 
	window._mvq = _mvq;
	_mvq.push(['$setAccount', 'm-27177-0']);

	_mvq.push(['$setGeneral', 'goodsdetail', '', /*用户名*/ '', /*用户id*/ '']);
	_mvq.push(['$logConversion']);

	_mvq.push(['setPageUrl', /*单品着陆页url*/ marketItemUrl]);	//如果不需要特意指定单品着陆页url请将此语句删掉
	_mvq.push(['$addGoods',  /*分类id*/ marketProductCateId, /*品牌id*/ marketBrandId, /*商品名称*/ marketProductName,/*商品ID*/ marketProductId,/*商品售价*/ marketSaleGuidePrice, /*商品图片url*/ bigImageUrl, /*分类名*/ marketBreadcrum, /*品牌名*/ marketBrandName, /*商品库存状态1或是0*/ stock, /*网络价*/ '',/*收藏人数*/ '', /*商品下架时间*/ '']);
	_mvq.push(['$addPricing', /*价格描述*/ '']);
	_mvq.push(['$logData']);
	firstEnterPage = 0;
}



function getLadderPrice(buyNumber){	
	if (ladderPrices.length == 0){return;}
	var isLadderPrice = false;
	for (var i = ladderPrices.length - 1; i >= 0 ; i--){
		if (parseInt(buyNumber) >= ladderPrices[i].num){
			$(".cur-price").html('￥' + ladderPrices[i].price);
			isLadderPrice = true;
			break;
		}
	}
	if (isLadderPrice == false){
		$(".cur-price").html('￥' + basePrice);
	}
}

function buildLadderPrice(data){
	for (var key in data){
		var lp = new Object();
		lp.num = key;
		if (data[key].toString().indexOf(".") < 0){
			lp.price = data[key] + ".00";
		}else{
			lp.price = data[key];
		}
		ladderPrices[ladderPrices.length] = lp;
	}
	//排序,排序后数据由小到大
	if (ladderPrices.length > 1){
		for (var i = 0; i < ladderPrices.length - 1; i++){			
			for (var j = i + 1; j < ladderPrices.length; j++){
				if (ladderPrices[j].num < ladderPrices[i].num){
					var min = ladderPrices[j];
					ladderPrices[j] = ladderPrices[i];
					ladderPrices[i] = min;
				}
			}
		}
	}
}

//必须在调用buildLadderPrice后调用，否则顺序可能不对
function getLadderPriceDescription(){
	var desc = '';
	for (var i = 0 ; i < ladderPrices.length ; i++){
		desc = desc + ' 购买' + ladderPrices[i].num + ' 件，价格 ' + ladderPrices[i].price + ';';  
	}
	return desc.substr(0,desc.length - 1) + "。";
}

function fillRight(content, maxlength, replaceStr){
	if (content){
		if (content.length > maxlength){
			return content.substring(0,maxlength-1) + replaceStr;
		}else{
			return content;
		}
	}	
}

function showPromotionInfo(){
	var cityId = $('.product-info').find('.js_fe_city').val();
	$.ajax({
        type : "post",
        url : itemDomain + "/product/ajaxgetpromotion.html",
        data: "productId=" + productId + "&regionId=" + cityId + "&" +getCSRFTokenParam(),
        contentType: "application/x-www-form-urlencoded; charset=utf-8", 
        success : function(data){
        	if (data.data.code == "0"){
        		if (data.data.ladderPrice != "" || data.data.coupons != ""){
        			$("#jsSoldNo").before("<li id='jsPromotion' style='position:relative;'><span class='s-title' style='height: 32px;'>促&nbsp;&nbsp;销：</span></li>");
        			if (data.data.ladderPrice != ""){
        				buildLadderPrice(data.data.ladderPrice);
        				$("#jsPromotion").append("<div style='float:left;width: 450px;'>"
        									   + "	<div class='ladprice-pop-lq'>阶梯价</div>"
        									   + "	<em class='blue lqemladp' style='display: inline-block; width: 330px; text-overflow: ellipsis; white-space: nowrap; overflow: hidden;'>" 
        									   + fillRight(getLadderPriceDescription(),35,"...") 
        									   + "	</em>"
        									   + "	<a href='javascript:void(0)' style='float:right;color:#2265aa;' class='takeonladp'>查看详情&gt;&gt;</a>"
        									   + "</div>"
        									   );
        				$("#jsPromotion").append("<div class='ladprice-pop' style='display: none;'>"
        									+ "	<div class='ladprice-pop-header'>"
        									+ "		<div class='coupon-pop-lq'>阶梯价</div>"
        									+ "		<a href='javascript:void(0)' class='takeoffladp'>关闭</a>"
        									+ "	</div>"
        									+ "	<div class='ladprice-pop-body clear-fix'>"
        									+ "		<span>"
        									+ getLadderPriceDescription()
        									+ "		</span>"
        									+ "	</div>"
        									+ "</div>"
        									);
        				resetLadderPriceBindEvent();
        			}
        			if (data.data.coupons != "" ){
        				if (data.data.coupons.length > 0){
        					$("#jsPromotion").append("<div style='float:left;width: 368px;'>"
        							+ "<div class='coupon-pop-lq'>领 券</div>"
        							+ "<em class='blue lqem'>先领券，再购买(点击领取下方优惠券)</em>"
        							+ "<a href='javascript:void(0)' style='float:right;color:#2265aa;' class='takeon'>共" + data.data.coupons.length + "项，查看详情&gt;&gt;</a>"
        							+ "</div>");
							var couponHeader = "<div class='coupon-pop' style='display: none;'>"
								+ "	<div class='coupon-pop-header'>"
								+ "		<div class='coupon-pop-lq'>领 券</div>"    		
								+ "			<a href='javascript:void(0)' class='takeoff'>关闭</a>"
								+ "		</div>"
								+ "	<div class='coupon-pop-body clear-fix'>";
        					var couponBody = "";
        					for (var i = 0 ; i < data.data.coupons.length ; i++){
        						couponBody = couponBody + "<div class='coupon-img' data-id='" + data.data.coupons[i].id + "'><a href='javascript:void(0)'><img src='" + itemDomain  + "/shoppingmall_item/resources/images/product/couponBg.jpg' alt='' data-coupon='满" + (data.data.coupons[i].term/100) + "立减,￥" + (data.data.coupons[i].amount/100) + "'></a><span class='coupon-full'>满" + (data.data.coupons[i].term/100) + "立减</span><span class='coupon-sale'>￥" + (data.data.coupons[i].amount/100) + "</span></div>"
        					}
        					var couponFooter = "</div></div>";
        					var couponContent = couponHeader + couponBody + couponFooter;
        					$("#jsPromotion").append(couponContent);
        					resetCouponBindEvent();
        				}
        			}
        			
        		}
        		if (data.data.couponsSelf != null){
        			for (var i = 0 ; i < data.data.couponsSelf.length ; i++){
        				$("#jsShopPr").append("<span style='height: 20px; line-height: 20px;background: #db3332 none repeat scroll 0% 0%; display: inline-block; text-align: center; color: rgb(255, 255, 255); margin-left: 10px; padding:0px 2px;'>"
    							+ data.data.couponsSelf[i].promotionName + "</span>");
					}
    				
    			}
        	}
        		
        	refrushCSRFToken(data.csrfToken);
        },
        error:function(){	        	
            refrushCSRFToken(data.csrfToken);
            return false;
        }
    });
}

function resetLadderPriceBindEvent(){
	$(".takeonladp,.ladprice-pop-lq,.lqemladp").click(function(){
		$(".ladprice-pop").css("display","block");
	});
	$(".takeoffladp").click(function(){
		$(".ladprice-pop").css("display","none");
	});
}

function resetCouponBindEvent(){
	$(".takeon,.coupon-pop-lq,.lqem").click(function(){
		$(".coupon-pop").css("display","block");
		var coupon = $('.coupon-pop-body').find('.coupon-img');
		$.each(coupon, function() {
			var couponImgArr = $(this).find('img').attr('data-coupon').split(',');
			$(this).find('.coupon-full').html(couponImgArr[0]);
			$(this).find('.coupon-sale').html(couponImgArr[1]);
		});
	});
	$(".takeoff").click(function(){
		$(".coupon-pop").css("display","none");
	});
	$(".coupon-img").on('click',function(){
		  var _this = this;
	      var url = baseDomain + "/coupons/lQCoupon";
		  var id = $(this).attr('data-id');
	      $.get(url,{'couponId':id,'timeFlag':Math.random()},function(data){
	        if("请先登录"==data){
	        	var ajaxUrl = memberDomain + "/ajaxLogin?callback=?";
					$.getJSON(ajaxUrl, function (data) {
					  var ajaxPop = $.sobox.pop({
						cls: 'ajax-popInfoBox',
						title: '用户登录',
						defaultShow: true,
						visibility: true,
						onlyOne: true,
						width: 340,
						content: data.data,
						async: false
					  });
					  ajaxPop.showPop();
					  $('body').data('ajaxPop', ajaxPop);
					});
	        }else{
	        	$.sobox.alert('提示', data);
	        }
		},"text");
	});
}
//我要预定
function doPredetermine() {
    var productId = $("#currentProductIdHidden").val();
    var buyNum = $("#buyNum").val();
    window.location.href = cartDomain + '/b2bPredetermineOrder.html?goodsId=' + productId + '&buyNum=' + buyNum;
}

//20160318  预售订单  begin
//显示预售规则
function showPreSaleRuleShow(){
    $(".preSaleRuleClass").show();
}
//隐藏预售规则
function showPreSaleRuleHide(){
    $(".preSaleRuleClass").hide();
}

var ProdObject=function(){
    this.productId=0;
    this.number=0;
};

var OrderProdObject=function(){
    this.activityId=0;
    this.products=new Array();
};
//执行预售
function doPresale() {
    var that = this;
    $.ajax({
        type: 'GET',
        url: rrs.memberDomain + '/headLoginAjax',
        dataType: 'jsonp',
        jsonp: 'callback',
        success: function (data) {
            if (data.isLogin === false) {
                var ajaxUrl = memberDomain + '/ajaxLogin?callback=?';
                $.getJSON(ajaxUrl, function (data) {
                    var ajaxPop = $.sobox.pop({
                        cls: 'ajax-popInfoBox',
                        title: '用户登录',
                        defaultShow: true,
                        visibility: true,
                        onlyOne: true,
                        width: 340,
                        content: data.data,
                        async: false,
                        callback: function () {
                            $('.ajax-popInfoBox .h2-sopop .s-title').text('用户登录');
                            $('.ajax-popInfoBox').css('visibility', 'visible').hide().fadeIn('fast');
                        }
                    });
                    ajaxPop.showPop();
                    $('body').data('ajaxPop', ajaxPop);
                });
            } else {

                var productId = $("#currentProductIdHidden").val();//商品ID
                var buyNum = $("#buyNum").val();//购买数量
                //window.location.href = cartDomain + '/b2bPredetermineOrder.html?goodsId=' + productId + '&buyNum=' + buyNum;

                // 遍历选择的商品
                var orderObject=new OrderProdObject();
                orderObject.activityId=8;//全额预售活动
                var num = $("#buyNum").val();
                var productId = $("#currentProductIdHidden").val();

                var newProd=new ProdObject();
                newProd.productId=Number(productId);
                newProd.number=Number(num) ;
                orderObject.products.push(newProd);
                var strMsg = JSON.stringify(orderObject)
                strMsg=encodeURI(strMsg);
                $("#jsonProducts").val(strMsg);
                $("#o2oform").submit();

            }
        },error: function () {
            $.sobox.alert('提示','对不起，服务器异常!');
            return false;
        }
    });
}

// 执行限时抢购/秒杀
function doFlashSale() {
    var that = this;
    $.ajax({
        type: 'GET',
        url: rrs.memberDomain + '/headLoginAjax',
        dataType: 'jsonp',
        jsonp: 'callback',
        success: function (data) {
            if (data.isLogin === false) {
                var ajaxUrl = memberDomain + '/ajaxLogin?callback=?';
                $.getJSON(ajaxUrl, function (data) {
                    var ajaxPop = $.sobox.pop({
                        cls: 'ajax-popInfoBox',
                        title: '用户登录',
                        defaultShow: true,
                        visibility: true,
                        onlyOne: true,
                        width: 340,
                        content: data.data,
                        async: false,
                        callback: function () {
                            $('.ajax-popInfoBox .h2-sopop .s-title').text('用户登录');
                            $('.ajax-popInfoBox').css('visibility', 'visible').hide().fadeIn('fast');
                        }
                    });
                    ajaxPop.showPop();
                    $('body').data('ajaxPop', ajaxPop);
                });
            } else {
                var productId = $("#currentProductIdHidden").val();//商品ID
                var buyNum = $("#buyNum").val();//购买数量
                // 遍历选择的商品
                var orderObject=new OrderProdObject();
                orderObject.activityId=10;//限时抢购/秒杀
                var num = $("#buyNum").val();
                var productId = $("#currentProductIdHidden").val();
                var newProd=new ProdObject();
                newProd.productId=Number(productId);
                newProd.number=Number(num) ;
                orderObject.products.push(newProd);
                var strMsg = JSON.stringify(orderObject)
                strMsg=encodeURI(strMsg);
                $("#jsonProducts").val(strMsg);
                $("#o2oform").submit();
            }
        },error: function () {
            $.sobox.alert('提示','对不起，服务器异常!');
            return false;
        }
    });
}
//服务端与前端时间差
var nowsecond;
var presalButten = 0;
function freshTimer() {
    var pres = $("#pre_isPresale").val();
    if(pres =="1"){
        if(nowsecond==undefined){
            var nowtimeBegin =new Date();//前端当前时间
            var nowtimeServerstr = $("#pre_nowAtStr").val();
            var nowtimeServer = new Date(nowtimeServerstr);//服务端当前时间
            nowsecond = nowtimeServer.getTime()-nowtimeBegin.getTime();//服务端与前端时间差
        }

        var nowtime = new Date();//当前系统时间
        var starttimestr = $("#pre_startAtStr").val();//预售开始时间
        var endtimestr = $("#pre_endAtStr").val();//预售结束时间
        var starttime = new Date(starttimestr);//预售开始时间
        var endtime=new Date(endtimestr);//预售结束时间
        var beginsecond=parseInt((starttime.getTime()-nowtime.getTime()+nowsecond)/1000);//预售开始时间与当前时间相差毫秒数
        if(beginsecond>0){
            //如果预售开始时间>当前系统时间,表示活动尚未开始
            //$("#times").html("活动还未开始，请稍后再来");
            presalButten=0;
            $(".p-product-btn").html(presaleNoStartHtml);
        }else{
            var leftsecond = parseInt((endtime.getTime()-nowtime.getTime()+nowsecond)/1000);//预售结束时间与当前时间相差毫秒数
            //如果预售结束时间小于当前时间，表示活动结束
            if(leftsecond<=0){
                //$("#times").html("抢购已结束");
                presalButten=0;
                $(".p-product-btn").html(presaleStopHtml);
                $("#presalestatus").html("已  结  束 ");
                clearInterval(sh);
            }else{
                sDay=parseInt(leftsecond/3600/24);
                sHour=parseInt((leftsecond/3600)%24);
                sMinute=parseInt((leftsecond/60)%60);
                sSecond=parseInt(leftsecond%60);
                var c=new Date();
                var q=((nowtime.getMilliseconds())%10);//当前时间毫秒数取余数
                if(presalButten==0){
                    $(".p-product-btn").html(presaleHtml);
                    presalButten = 1;
                }
                $("#times").html("还剩: "+sDay+"天"+sHour+"小时"+sMinute+"分"+sSecond+"."+q+"秒");
                $("#presalestatus").html("进  行  中 ");
            }
        }

    }else{
        clearInterval(sh);
    }

}
freshTimer()
var sh;
sh=setInterval(freshTimer,100);
//20160318  预售订单  end

var flashSaleNowsecond;
var timeCount=0;
function flashSaleFreshTimer() {
    var isFlashSale = $("#flash_isFlashSale").val();
    var flashSale_type = $("#flashSale_type").val();
    var flashSale_price = $("#flashSale_price").val();
    var flashSale_status = $("#flashSale_status").val();
    if(isFlashSale =="1" && flashSale_type=="2" ){
        if(flashSaleNowsecond==undefined){
            var nowtimeBegin =new Date();//前端当前时间
            var nowtimeServerstr = $("#flash_nowAtStr").val();
            var nowtimeServer = new Date(nowtimeServerstr);//服务端当前时间
            flashSaleNowsecond = nowtimeServer.getTime()-nowtimeBegin.getTime();//服务端与前端时间差
        }

        var nowtime = new Date();//当前系统时间
        var starttimestr = $("#flash_startAtStr").val();//开始时间
        var endtimestr = $("#flash_endAtStr").val();//结束时间
        var starttime = new Date(starttimestr);//开始时间
        var endtime=new Date(endtimestr);//结束时间
        var beginsecond=parseInt((starttime.getTime()-nowtime.getTime()+flashSaleNowsecond)/1000);//预售开始时间与当前时间相差毫秒数
        if( beginsecond > 0 ){
            //如果开始时间>当前系统时间,表示活动尚未开始
        	++timeCount;
        	sMinute = parseInt(beginsecond/60);
            sSecond=parseInt(beginsecond%60);
            
            $("#flash_times").html("距活动开始：还有<span style='display: inline-block;width: 22px;height: 22px;background: #c7003a;text-align: center;line-height: 20px;vertical-align: middle;border-radius: 4px;margin: 0 4px;color: #fff;'>"+sMinute+"</span>分<span style='display: inline-block;width: 22px;height: 22px;background: #c7003a;text-align: center;line-height: 20px;vertical-align: middle;border-radius: 4px;margin: 0 4px;color: #fff;'>"+sSecond+"</span>秒");
        }else{
            var leftsecond = parseInt((endtime.getTime()-nowtime.getTime()+flashSaleNowsecond)/1000);//预售结束时间与当前时间相差毫秒数
            if( timeCount > 0 ){//从未开始到活动开始
            	
            	if( isMainProStock ){
                	$(".p-product-btn").html(flashSaleHtml);
                }else{
                	$(".p-product-btn").html(noStockHtml);
                }
            	//修改购买状态
            	$("#jsMallPrice .cur-price").addClass("no-price");
            	$("#jsMallPrice .cur-price").removeClass("cur-price");
            	$("#jsShopPr  .cur-price").addClass("haierred");
            	$("#jsShopPr  .cur-price").html("￥"+flashSale_price);
            	flashSaleButten = 1;
        	}
            //如果预售结束时间小于当前时间，表示活动结束
            if( leftsecond <= 0 ){
            	$("#flash_times").html("活动已结束");
            	$(".p-product-btn").html("");
            	clearInterval(flashSaleSH);
            	//var productId = $("#currentProductIdHidden").val();//商品ID
            	//window.location.href = itemDomain + "/product/"+productId+".html";
            }else{
                //sDay=parseInt(leftsecond/3600/24);
                //sHour=parseInt((leftsecond/3600)%24);
                //sMinute=parseInt((leftsecond/60)%60);
                sMinute = parseInt(leftsecond/60);
                sSecond=parseInt(leftsecond%60);
                //if(presalButten==0){
                //    $(".p-product-btn").html(presaleHtml);
                //    presalButten = 1;
                //}
                $("#flash_times").html("距活动结束：还有<span style='display: inline-block;width: 22px;height: 22px;background: #c7003a;text-align: center;line-height: 20px;vertical-align: middle;border-radius: 4px;margin: 0 4px;color: #fff;'>"+sMinute+"</span>分<span style='display: inline-block;width: 22px;height: 22px;background: #c7003a;text-align: center;line-height: 20px;vertical-align: middle;border-radius: 4px;margin: 0 4px;color: #fff;'>"+sSecond+"</span>秒");
                //$("#presalestatus").html("进  行  中 ");
            }
        }

    }else if(isFlashSale =="1" && flashSale_type=="1" ){
        if(flashSaleNowsecond==undefined){
            var nowtimeBegin =new Date();//前端当前时间
            var nowtimeServerstr = $("#flash_nowAtStr").val();
            var nowtimeServer = new Date(nowtimeServerstr);//服务端当前时间
            flashSaleNowsecond = nowtimeServer.getTime()-nowtimeBegin.getTime();//服务端与前端时间差
        }
        var nowtime = new Date();//当前系统时间
        var starttimestr = $("#flash_startAtStr").val();//开始时间
        var endtimestr = $("#flash_endAtStr").val();//结束时间
        var starttime = new Date(starttimestr);//开始时间
        var endtime=new Date(endtimestr);//结束时间
        var beginsecond=parseInt((starttime.getTime()-nowtime.getTime()+flashSaleNowsecond)/1000);//预售开始时间与当前时间相差毫秒数
        if( beginsecond > 0 ){
            //如果开始时间>当前系统时间,表示活动尚未开始
        	sMinute = parseInt(beginsecond/60);
            sSecond=parseInt(beginsecond%60);
            //$("#flash_times").html("距活动开始：还有"+sMinute+"分"+sSecond+"秒");
        }else{
            var leftsecond = parseInt((endtime.getTime()-nowtime.getTime()+flashSaleNowsecond)/1000);//预售结束时间与当前时间相差毫秒数
            //如果预售结束时间小于当前时间，表示活动结束
            if( leftsecond <= 0 ){
            	$("#flash_times").html("活动已结束");
            	$(".p-product-btn").html("");
            	clearInterval(flashSaleSH);
            	//var productId = $("#currentProductIdHidden").val();//商品ID
            	//window.location.href = itemDomain + "/product/"+productId+".html";
            }
        }

    }else{
        clearInterval(flashSaleSH);
    }

}
flashSaleFreshTimer();
var flashSaleSH;
flashSaleSH=setInterval(flashSaleFreshTimer,100);
//限时抢购/秒杀  end

//组合套餐加入结算页，立即购买
function addToCustomizeOrder() {
	//是否选中地区
	var $_root = $('.product-info');
	var $region = $_root.find('.js_fe_region');
    if ( parseInt( $region.val() ) ) {
    	
    } else {
        $('.deliver-tip').addClass('red');
        $('.sel-location-box').fadeIn();
        return false;
    }
	//var productId = $("#currentProductIdHidden").val();//商品ID
    //var buyNum = $("#buyNum").val();//购买数量
    
    var that = this;
    $.ajax({
        type: 'GET',
        url: rrs.memberDomain + '/headLoginAjax',
        dataType: 'jsonp',
        jsonp: 'callback',
        success: function (data) {
            if (data.isLogin === false) {
                var ajaxUrl = memberDomain + '/ajaxLogin?callback=?';
                $.getJSON(ajaxUrl, function (data) {
                    var ajaxPop = $.sobox.pop({
                        cls: 'ajax-popInfoBox',
                        title: '用户登录',
                        defaultShow: true,
                        visibility: true,
                        onlyOne: true,
                        width: 340,
                        content: data.data,
                        async: false,
                        callback: function () {
                            $('.ajax-popInfoBox .h2-sopop .s-title').text('用户登录');
                            $('.ajax-popInfoBox').css('visibility', 'visible').hide().fadeIn('fast');
                        }
                    });
                    ajaxPop.showPop();
                    $('body').data('ajaxPop', ajaxPop);
                });
            } else {
                var mainProductId = $("#currentProductIdHidden").val();//商品ID
                var buyNum = $("#buyNum").val();//购买数量
                
                var customizeType_id = $("#customizeType_id");
                var customizeId = customizeType_id.attr("customizeId");
                
                var arrProdcuts = [{productId:mainProductId, number:buyNum}];
    			
    			var isChoose = false;
                $("[id^='customizeId_']").each(function(index, element) {
                	var numCustomize = $(this).attr('value');
                	if("0" != numCustomize){
                		isChoose = true;
                		var customizeProId = $(this).attr('customizeProId');
                		arrProdcuts.push( {productId:customizeProId,number:numCustomize} );
                	}
                })
                if( !isChoose ){
                	$.sobox.alert('提示', '请选择搭配套餐商品！');
                	return;
                }
                var jsonProducts = JSON.stringify(arrProdcuts);
                //alert(jsonProducts.replace(/\"/g,""));
                window.location.href = cartDomain + '/customizeOrder.html?mainProductId=' + mainProductId + '&activityId=' + 9+'&jsonProducts='+jsonProducts.replace(/\"/g,"") ;
//                var posturl = cartDomain + '/customizeOrder.html';
//                $.ajax({
//                	  type: 'POST',
//                	  url: posturl,
//                	  async: false,
//                	  data: 'mainProductId=' + mainProductId + '&activityId=' + 9 +'&jsonProducts='+jsonProducts + "&" +getCSRFTokenParam(),
//                	  //data: { "mainProductId": mainProductId, "activityId": 9, "jsonProducts":jsonProducts, "tmp":getRandomStr() },
//                	  error: function(data) {
//                		  $.sobox.alert('提示', '服务异常，请稍后再试！');
//                	  }
//                });
            }
        },
        error: function () {
            $.sobox.alert('提示','对不起，服务器异常!');
            return false;
        }
    });
}

//计算搭配套餐所选商品数量和价格
function sumCustomizeNumAndPrice(){
	
	//限时抢购 限制购买数量
	var flashSale_number = $("#flashSale_number").val();
	var flashSale_status = $("#flashSale_status").val();
	if( flashSale_number !="" && flashSale_number !="0" && flashSale_status=="2"){
		var buyNum = $('.s-pro-num .txt-num').val();//判断主商品 数量
		if( Number(buyNum) > Number(flashSale_number) ){
			$(".s-pro-num .txt-num").val(flashSale_number);
			$.sobox.alert("提示","每人限购"+flashSale_number+"件！");
			return;
		}
	}
	
	
	var productPrice = 0;
	var customizeHtml = "";//购买详情
	var customizeDiscountHtml = 0;//优惠金额
	var customizeSalePriceAll = 0;
	var customizeDiscountExpression = "";
	
	var mainProAllCount =0;
	var $txtNum = $('.s-pro-num .txt-num');//判断主商品 数量
	var nv = parseInt($txtNum.val());
	mainProAllCount = Number( nv*basePrice );
	
	var allCount = 0;
	//判断套餐类型1-购就减  2-满减
	var customizeType = $('#customizeType_id').attr("value");
	if( "1" == customizeType || "2" == customizeType){
		for (var i = 0; i < 6; i++) {
			$tp = $('#customizeId_'+i);
			if( $tp.length>0 ){ //判断id是否存在
				if( "0" != $tp.attr("value") ){
					var num = $tp.attr("value");
					var customizeDiscount = $tp.attr("customizeDiscount");
					customizeHtml += num + "*" + $tp.attr('customizeSimpleName') +" ";
					customizeDiscountHtml += (Number(num) * Number(customizeDiscount));
					
					var customizeSalePrice = $tp.attr("customizeSalePrice");//套餐商品销售价格
					customizeSalePriceAll += (Number(num) * Number(customizeSalePrice) );
					
					if( "1" == customizeType ){
						if( customizeDiscountExpression == ""){
							customizeDiscountExpression +=  num +"*"+ customizeDiscount
						}else{
							customizeDiscountExpression +=  "+"+num +"*"+ customizeDiscount
						}
					}
				}
			}
		}
	}
	if("1" == customizeType){
		allCount = Number(mainProAllCount) + Number(customizeSalePriceAll ) - Number(customizeDiscountHtml);
	}
	if( "2" == customizeType){
		var allCount_3 = 0;
		for (var i = 0; i < 3; i++){
			$customizeDiscount = $('#customizeDiscountId_'+i);
			if( $customizeDiscount.length>0 ){ //判断id是否存在
				var discountDiscountType = $customizeDiscount.attr('discountDiscountType');//满减方式：1-直减 2-折扣
				var discountTerm = $customizeDiscount.attr('discountTerm');
				var discountAmount = $customizeDiscount.attr('discountAmount');
				var discountRate = $customizeDiscount.attr('discountRate');
				if( "1" == discountDiscountType){ //满减
					var allCount_2 = Number(mainProAllCount) + Number(customizeSalePriceAll ) ;
					if( Number( allCount_2.toFixed(2) ) >= Number( discountTerm ) ){
						customizeDiscountHtml = discountAmount;
						customizeDiscountExpression = "满"+discountTerm+"减"+discountAmount;
						allCount_3 = Number( allCount_2 ) - Number(discountAmount);
						allCount = Number( allCount_2 ) - Number(discountAmount);
					}else{ //如果不满足该满减条件，则用满足条件的
						if( 0 != allCount_3 ){
							allCount = allCount_3;
						}else{
							allCount = allCount_2 ;
						}
					}
				}else if( "2" == discountDiscountType){ //折扣
					var allCount_2  = Number(mainProAllCount) + Number(customizeSalePriceAll ) ;
					if( Number( allCount_2.toFixed(2) ) >= Number( discountTerm) ){
						customizeDiscountExpression = discountRate+"折优惠";
						customizeDiscountHtml = Number( allCount_2 ) * ( Number(10) - Number(discountRate) )/10;
						allCount_3 = allCount = ( Number(mainProAllCount) + Number(customizeSalePriceAll ) ) * Number(discountRate)/Number(10);
						allCount = allCount = ( Number(mainProAllCount) + Number(customizeSalePriceAll ) ) * Number(discountRate)/Number(10);
					}else{
						if( 0 != allCount_3 ){
							allCount = allCount_3;
						}else{
							allCount = allCount_2 ;
						}
					}
				}
			}
		}
	}
	if( $('#customizeId_0').length > 0 ){ //判断是否存在搭配套餐商品
		$('#customize_display_id').html(customizeHtml);
		if( customizeSalePriceAll != 0 ){
			if( customizeDiscountExpression == ""){
				$('#customize_discount_id').html( Number(customizeDiscountHtml).toFixed(2) +"元 "  ); //保留两位小数
			}else{
				$('#customize_discount_id').html( Number(customizeDiscountHtml).toFixed(2) +"元 (" + customizeDiscountExpression +")" ); //保留两位小数
			}
			$('#customize_total_id').html(  Number(allCount).toFixed(2)  +"元 " ); //主商品 + 套餐金额，主商品只用基础价格
		}else{
			$('#customize_discount_id').html("");
			$('#customize_total_id').html(""); //主商品 + 套餐金额，主商品只用基础价格
		}
	}
	
}

//显示送货区域
function showRegionLocation(){
    $('html, body').stop().animate({scrollTop:$('#product_info').offset().top});
    $('.deliver-tip').addClass('red');
    $('.sel-location-box').fadeIn();
}
function showArrival(){
	$('.so-popbox-mask').show();
	$('.ajax-arrival').show();
}
function addArrivalMobile(){
    var productId = $("#currentProductIdHidden").val();
    $("#mobile").text($("#arrivalMobile").val());
    var mobile = $("#arrivalMobile").val();
    if(mobile==null || mobile==''){
    	 $("#arrivalMobile").attr("placeholder","手机号不能为空!");
    	 $("#arrivalMobile").focus();
    	 return false;
    }
    var reg = /^[1][34578]\d{9}$/;
    if(!reg.test(mobile)){
    	$("#arrivalMobile").val('');
    	$("#arrivalMobile").attr("placeholder","手机号码格式不正确!");
    	$("#arrivalMobile").focus();
    	return false;
    }
    $.ajax({
        type : "post",
        url : itemDomain + "/product/addArrivalNotice.html",
        data: "productId=" + productId + "&mobile=" + mobile  +  "&" +getCSRFTokenParam(),
        contentType: "application/x-www-form-urlencoded; charset=utf-8", 
        success : function(data){
    		$('.so-popbox-mask').hide();
    		$('.ajax-arrival').hide();
            if (data.data.code==0){
            	 $.sobox.alert('您的资料已提交成功', '到货后,我们将第一时间通知您! 感谢您使用日日顺健康平台！');
            	 $("#arrivalMobile").val('');
                 refrushCSRFToken(data.csrfToken);
            }else{
            	$.sobox.alert('提示', data.data.message);
                refrushCSRFToken(data.csrfToken);
            }
        },
        error:function(){
        	$('.so-popbox-mask').hide();
    		$('.ajax-arrival').hide();
        	$.sobox.alert('提示', '抱歉，您的请求未能提交成功，请刷新页面重试！');
            refrushCSRFToken(data.csrfToken);
        }
    });
}
